// 导入模块
import { useUserStore } from "@/stores/user";
import Request, { type HttpMethod, type HttpRequestConfig } from "luch-request";

// 实例化网络请求
const service = new Request({
  // 接口基地址
  baseURL: "https://consult-api.itheima.net",
  timeout: 15 * 1000,
  custom: {
    loading: true,
  },
});

// 接口白名单
const whiteList = ["/code", "/login", "/login/password"];

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (config.custom?.loading) {
      uni.showLoading({
        title: "加载中...",
        mask: true,
      });
    }
    // 添加 token，排除白名单情况
    const store = useUserStore();
    if (store.token && config.url && !whiteList.includes(config.url)) {
      config.header = {
        ...config.header,
        Authorization: `Bearer ${store.token}`,
      };
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    uni.hideLoading();
    // 业务状态码，后端约定，code === 10000 为成功
    if (res.data.code !== 10000) {
      uni.showToast({
        title: res.data.message,
        icon: "none",
      });
      return Promise.reject(res.data);
    }
    return res.data;
  },
  (error) => {
    // 401 状态码，后端约定，未登录或登录过期
    if (error.data.code === 401) {
      uni.showToast({
        title: error.data.message,
        icon: "none",
      });
      // 清除 token
      const store = useUserStore();
      store.clearToken();
      // 跳转登录页
      uni.navigateTo({ url:'pages/login/login' })
    }
    return Promise.reject(error);
  }
);

// 服务端响应数据结构
export interface ServiceResponse<T> {
  code: number;
  message: string;
  data: T;
}

// 封装请求工具
const request = <T>(
  url: string,
  method: HttpMethod = "GET",
  submitData?: object,
  config?: HttpRequestConfig // 请求配置
) => {
  return service.request<T, ServiceResponse<T>>({
    url: url,
    method: method,
    [method.toUpperCase() === "GET" ? "params" : "data"]: submitData,
    ...config,
  });
};

export { service, request };
